<template>
  <div class="gift-recommend-page">
    <div class="container">
      <div class="header">
        <h2>为你找到这些礼物</h2>
        <div class="conditions">
          <el-tag type="info">送给：{{ query.recipient }}</el-tag>
          <el-tag type="success">场合：{{ query.occasion }}</el-tag>
          <el-tag type="warning" v-for="t in traitList" :key="t">{{ t }}</el-tag>
          <el-tag type="danger">预算：{{ query.budget }}</el-tag>
        </div>
      </div>

      <el-empty v-if="loading && products.length===0" description="正在为你挑选..." />

      <div v-else class="product-grid">
        <div v-for="(item, idx) in topRecommendations" :key="item.id || idx" class="product-item">
          <div class="product-card" @click="toDetails(item)">
            <el-image :src="item.mainImg" fit="cover"/>
            <div class="info">
              <div class="name" :title="item.name">{{ item.name }}</div>
              <div class="price">¥{{ item.price }}</div>
              <div class="reason">推荐理由：{{ buildReason(item) }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="actions">
        <el-button @click="backToIndex">返回首页</el-button>
        <el-button type="primary" @click="refine">调整条件再试</el-button>
      </div>
    </div>
    <Footer />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import request from '@/utils/http.js'

const route = useRoute()
const router = useRouter()

const query = ref({
  recipient: route.query.recipient || '',
  occasion: route.query.occasion || '',
  traits: route.query.traits || '',
  budget: route.query.budget || ''
})

const traitList = computed(() => (query.value.traits ? String(query.value.traits).split(',').filter(Boolean) : []))

const products = ref([])
const loading = ref(true)

// 简单预算解析为区间
function parseBudgetRange(budget) {
  switch (budget) {
    case '100元内':
      return [0, 100]
    case '100-300元':
      return [100, 300]
    case '300-800元':
      return [300, 800]
    case '800元以上':
      return [800, Number.MAX_SAFE_INTEGER]
    default:
      return [0, Number.MAX_SAFE_INTEGER]
  }
}

// 预算优先：先判断是否在预算内，再比较离预算区间中点的距离，最后再比较标签与热度
function inBudget(p, ctx) {
  const [min, max] = parseBudgetRange(ctx.budget)
  const price = Number(p.price)
  return Number.isFinite(price) && price >= min && price <= max
}

function budgetDistance(p, ctx) {
  const [min, max] = parseBudgetRange(ctx.budget)
  const price = Number(p.price)
  const mid = (min + max) / 2
  if (!Number.isFinite(price)) return Number.POSITIVE_INFINITY
  return Math.abs(price - mid)
}

// 标签匹配打分：traits/recipient/occasion/热度
function tagAndPopularityScore(p, ctx) {
  let score = 0
  const tags = (p.tags || '').split(',').filter(Boolean)
  const traitMatches = ctx.traits.filter(t => tags.includes(t)).length
  score += traitMatches * 3
  if (ctx.recipient && tags.includes(ctx.recipient)) score += 2
  if (ctx.occasion && tags.includes(ctx.occasion)) score += 2
  if (p.salesVolume) score += Math.min(3, p.salesVolume / 1000)
  if (p.score) score += Math.min(2, p.score / 2.5)
  return score
}

const topRecommendations = computed(() => {
  if (!products.value || products.value.length === 0) return []
  const ctx = {
    recipient: query.value.recipient,
    occasion: query.value.occasion,
    traits: traitList.value,
    budget: query.value.budget
  }

  // 预算优先排序：
  // 1) 是否在预算内（true 优先）
  // 2) 离预算中点越近越好（距离更小更优）
  // 3) 标签与热度得分更高者优先
  const ranked = products.value
    // 仅保留预算范围内的商品
    .filter(p => inBudget(p, ctx))
    .map(p => ({
      p,
      dist: budgetDistance(p, ctx),
      tagScore: tagAndPopularityScore(p, ctx)
    }))
    .sort((a, b) => {
      if (a.dist !== b.dist) return a.dist - b.dist
      return b.tagScore - a.tagScore
    })
    .slice(0, 5)
    .map(x => x.p)

  return ranked
})

function buildReason(p) {
  const tags = (p.tags || '').split(',').filter(Boolean)
  const tMatch = traitList.value.find(t => tags.includes(t))
  if (tMatch) return `${tMatch}倾向，贴合对方喜好`
  if (query.value.occasion && tags.includes(query.value.occasion)) return `适合${query.value.occasion}场合`
  if (query.value.recipient && tags.includes(query.value.recipient)) return `适合送给${query.value.recipient}`
  return '人气与价格较为合适'
}

function loadProducts() {
  loading.value = true
  // 拉一页较多商品供前端打分
  request.get('/product/page', { params: { pageNum: 1, pageSize: 200 } })
    .then(res => {
      products.value = res.data.list || []
    })
    .finally(() => {
      loading.value = false
    })
}

function toDetails(item) {
  router.push(`/front/productDetails/${item.id}`)
}

function backToIndex() {
  router.push('/front/index')
}

function refine() {
  // 回到首页唤起弹窗（通过事件总线或简单方案：跳首页，用户再点按钮）
  router.push('/front/index')
}

onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.gift-recommend-page {
  background: #f5f5f5;
  min-height: 100vh;
}

/* 仅在本页面为 Header 区域设置背景图 */
:deep(.header) {
  background: url('@/assets/index_bg.png') no-repeat center top;
  background-size: 100% auto;
}

.container {
  width: 1190px;
  margin: 0 auto;
  padding: 20px 0;
}

.header {
  background: #fff;
  padding: 16px 20px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.conditions {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}

.product-item .product-card {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.product-item .product-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  border-color: #e1251b;
}

.product-item :deep(.el-image) {
  width: 100%;
  height: 180px;
}

.info { padding: 12px; }
.name { font-size: 14px; color: #333; line-height: 20px; height: 40px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
.price { color: #e1251b; font-weight: bold; margin-top: 6px; }
.reason { font-size: 12px; color: #666; margin-top: 6px; }

.actions { display: flex; justify-content: center; gap: 12px; margin: 20px 0; }
</style>


